from flask import Blueprint, request, make_response, render_template, url_for, redirect

from functools import wraps
from Crypto.Cipher import ARC4
import base64
import time

admin = Blueprint("admin", __name__)

cookie_key="dea3212fasdf323afasf"

def rc4(key, data):
    r = ARC4.new(key)
    d = r.encrypt(data)
    return d

def is_login():
    c = request.cookies.get("mloginuid")
    if not c:
        #return redirect("/login")
        return False
    c1 = rc4(cookie_key, base64.b64decode(c))
    if c1.startswith("admin_AUTH"):
        return True
    return False

def login_required(fn):
    @wraps(fn)
    def check_login(*args, **kargs):
        if is_login():
            return fn(*args, **kargs)
        else:
            return redirect(url_for("admin.login", next=request.url))
    return check_login

@admin.route("/logout")
def logout():
    next_p=request.values.get("next")
    if not next_p:
        next_p = url_for("msg_push.push")
    rs=make_response(redirect(next_p))
    rs.set_cookie("mloginuid","")
    return rs

@admin.route("/login", methods=["GET", "POST"])
def login():
    username = request.values.get("username")
    passwd = request.values.get("password")
    n = request.values.get("next")
    path = request.values.get("path")
    if not n:
        r1 = request.headers.get("referer")
        if r1:
            n = r1
    if not username or not passwd:
        if not n:
            n="push"
        return render_template("login.html")

    if username == "admin" and passwd == "nimda":
        r =redirect(n) if n else redirect("push")
        rs = make_response(r)
        rs.set_cookie("mloginuid",
                base64.b64encode(rc4(cookie_key, "admin_AUTH_%s" % time.strftime("%Y-%m-%d %H:%M:%S"))),
                max_age=30*24*60*60,
                path = path if path else "/",
                )
        return rs

    return render_template("login.html", error_msg="login faied")
